package com.trip.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class OneSignalUtil {
	private static final Logger logger= LoggerFactory.getLogger(OneSignalUtil.class);

	private static final String APP_ID = "87d88280-0599-4fe2-800a-5d909d2aac34";
	private static final String SERVER_KEY = "MzdmODU2NzYtYTkxZi00ZDc1LTliZDMtYzhmZmYzNDc0ODJi";

	private static final String MESSAGE_TEMPLATE="You have a message from %S";

	public static void pushMessage(List<String> userIds,String planName){
		try {
			sendPush2Tag("userId", userIds, String.format(MESSAGE_TEMPLATE, planName));
		}catch (Exception e){
			logger.warn("Push messae error",e);
		}
	}

	private static HttpURLConnection getConnection() throws Exception{
		HttpURLConnection con=null;
		URL url;

		url = new URL("https://onesignal.com/api/v1/notifications");
		con = (HttpURLConnection) url.openConnection();
		con.setUseCaches(false);
		con.setDoOutput(true);
		con.setDoInput(true);
		con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
		con.setRequestProperty("Authorization", "Basic " + SERVER_KEY);
		con.setRequestMethod("POST");

		return con;

	}

	/**
	 * send to all devices
	 */
	public static void send2All() {
		try {
			String jsonResponse;
			String msg = "Hello we update 3 palces";
			String strJsonBody = "{" + "\"app_id\": \"" + APP_ID + "\"," + "\"included_segments\": [\"All\"],"
					+ "\"data\": {\"foo\": \"bar\"}," + "\"contents\": {\"en\": \"" + msg + "\"}" + "}";

			System.out.println("strJsonBody:\n" + strJsonBody);
			byte[] sendBytes = strJsonBody.getBytes("UTF-8");

			HttpURLConnection connection = getConnection();
			connection.setFixedLengthStreamingMode(sendBytes.length);
			OutputStream outputStream = connection.getOutputStream();
			outputStream.write(sendBytes);
			int httpResponse = connection.getResponseCode();
			if (200 == httpResponse) {
				logger.info("success");
			} else {
				logger.info("fail");
			}
			logger.info("httpResponse: " + httpResponse);

			if (httpResponse >= HttpURLConnection.HTTP_OK && httpResponse < HttpURLConnection.HTTP_BAD_REQUEST) {
				Scanner scanner = new Scanner(connection.getInputStream(), "UTF-8");
				jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
				scanner.close();
			} else {
				Scanner scanner = new Scanner(connection.getErrorStream(), "UTF-8");
				jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
				scanner.close();
			}
			logger.info("jsonResponse:\n" + jsonResponse);

		} catch (Throwable t) {
			t.printStackTrace();
		}

	}

	public static void sendPush2Tag(String tag, String tagValue, String pushContent) {

	}

	public static void sendPush2Tag(String tag, List<String> tagValueList, String pushContent) {
		HttpURLConnection connection=null;
		try {

			String jsonResponse;
			StringBuilder tags = new StringBuilder();
			int i=0;
			for(String tagValue:tagValueList) {
				tags.append("{\"field\": \"tag\", \"key\": \""+tag+"\", \"relation\": \"=\", \"value\": \""+tagValue+"\"}");
				if(i<tagValueList.size()-1){
					tags.append(",{\"operator\": \"OR\"},");
				}
				i++;
			}
			String strJsonBody =  "{"
					+   "\"app_id\": \""+APP_ID+"\","
					+   "\"filters\": ["+tags.toString()+"],"
					+   "\"data\": {\"foo\": \"bar\"},"
					+   "\"contents\": {\"en\": \""+pushContent+"\"},"
					+	 "\"ios_badgeType\": \"Increase\","
					+	 "\"ios_badgeCount\": 1"
					+ 	"}";

			logger.info("strJsonBody:\n" + strJsonBody);
			byte[] sendBytes = strJsonBody.getBytes("UTF-8");

			connection = getConnection();
			connection.setFixedLengthStreamingMode(sendBytes.length);

			OutputStream outputStream = connection.getOutputStream();
			outputStream.write(sendBytes);
			int httpResponse = connection.getResponseCode();

			logger.info("httpResponse: " + httpResponse);

			if (httpResponse >= HttpURLConnection.HTTP_OK && httpResponse < HttpURLConnection.HTTP_BAD_REQUEST) {
				Scanner scanner = new Scanner(connection.getInputStream(), "UTF-8");
				jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
				scanner.close();
			} else {
				Scanner scanner = new Scanner(connection.getErrorStream(), "UTF-8");
				jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
				scanner.close();
			}
			logger.info("jsonResponse:\n" + jsonResponse);

		} catch (Throwable t) {
			logger.warn("Push error",t);
		}finally{
			if(connection!=null)
				connection.disconnect();
		}

	}

	public static void main(String[] args) {
		sendPush2Tag("userId", Arrays.asList("12274","12258"), "User 1 you have message by hjc");
//		sendPush2Tag("groupId", "14", "hello you have a message not read from group Test");
		// send2All();
	}

	// ========================================sample code
	// below========================================================================================================================
	void template() {
		try {
			String jsonResponse;

			URL url = new URL("https://onesignal.com/api/v1/notifications");
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setUseCaches(false);
			con.setDoOutput(true);
			con.setDoInput(true);

			con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
			con.setRequestProperty("Authorization", "Basic " + SERVER_KEY);
			con.setRequestMethod("POST");

			// send 2 person
			// String tags="[{\"key\": \"userid\", \"relation\": \"=\",
			// \"value\": \"123\"},{\"operator\": \"OR\"},{\"key\": \"userid\",
			// \"relation\": \"=\", \"value\": \"125\"}]";
			// send 2 person
			String tags = "[{\"key\": \"userId\", \"relation\": \"=\", \"value\": \"113\"}]";

			String msg = "Hello from eclipse by sand";
			String strJsonBody = "{" + "\"app_id\": \"" + APP_ID + "\"," + "\"included_segments\": [\"All\"]," + "\"isIos\": true,"// allow
																																	// to
																																	// send
																																	// ios
					+ "\"isAndroid\": true,"// allow to send android
					+ "\"data\": {\"alert\": \"hello sand eclipse ground \",\"title\":\"Test\"}," + "\"android_background_data\": true,"
					// + "\"tags\""+":"+tags+","
					+ "\"contents\": {\"en\": \"hello sand eclipse\"}"// send
																		// ios
																		// use
																		// this
																		// ,if
																		// send
																		// to
																		// android
																		// delete
																		// this
																		// line
					+ "}";

			System.out.println("strJsonBody:\n" + strJsonBody);

			byte[] sendBytes = strJsonBody.getBytes("UTF-8");
			con.setFixedLengthStreamingMode(sendBytes.length);

			OutputStream outputStream = con.getOutputStream();
			outputStream.write(sendBytes);

			int httpResponse = con.getResponseCode();
			System.out.println("httpResponse: " + httpResponse);

			if (httpResponse >= HttpURLConnection.HTTP_OK && httpResponse < HttpURLConnection.HTTP_BAD_REQUEST) {
				Scanner scanner = new Scanner(con.getInputStream(), "UTF-8");
				jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
				scanner.close();
			} else {
				Scanner scanner = new Scanner(con.getErrorStream(), "UTF-8");
				jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
				scanner.close();
			}
			System.out.println("jsonResponse:\n" + jsonResponse);

		} catch (Throwable t) {
			t.printStackTrace();
		}
	}
}
